<template>
  <div class="menu-container">
    <!-- 左侧tab切换区域 -->
    <div class="left-panel">
      <!-- 日期选择器 -->
      <div class="date-picker">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 250px"
          @change="onDateChange"
        />
      </div>
      <div class="scrollable-area" ref="scrollableArea" @scroll="handleScroll">
        <div class="person-list">
          <!-- 左侧tab切换-->
          <div
            class="person-card"
            :class="{ selected: selectedPerson == index }"
            v-for="(item, index) in tabsList"
            :key="index"
            @click="selectPerson(index)"
          >
            <div class="person-header">
              <span class="person-name">{{
                item.history_version
                  ? "第" +
                    (item.history_version ? item.history_version : 0) +
                    "期菜谱"
                  : "暂无菜谱"
              }}</span>
            </div>
            <div style="text-align: right">
              <span
                class="person-name"
                style="font-weight: normal; font-size: 13px"
                >{{
                  item.history_begin_date
                    ? item.history_begin_date + "至" + item.history_end_date
                    : "暂无日期"
                }}</span
              >
            </div>

            <div class="check-icon" v-if="selectedPerson == index">
              <i class="el-icon-check"></i>
            </div>
          </div>
        </div>
        <!-- 加载更多提示 -->
        <div v-if="loadingMore" class="loading-more">
          <i class="el-icon-loading"></i>
          <span>加载中...</span>
        </div>

        <!-- 没有更多数据提示 -->
        <div v-if="!hasMoreData && tabsList.length > 0" class="no-more-data">
          没有更多数据了
        </div>
      </div>
    </div>
    <!-- 右侧菜单表格区域 -->
    <div class="right-panel">
      <div class="menu-table-container">
        <!-- 添加容器将标题和按钮放在同一行 -->
        <div class="title-actions-container">
          <div>
            <div style="display: flex">
              <h2 class="table-title">{{ "第" + title + "期菜谱" }}</h2>
              <span style="padding-left: 20px">({{ seletedTime }})</span>
            </div>
          </div>

          <!-- 顶部按钮区域 -->
          <div
            class="actions-wrapper"
            style="display: flex; align-items: center"
          >
            <el-button
              v-if="selectedPerson !== 0"
              style="background-color: #4c6ee2; color: white"
              size="small"
              @click="handleSubmit('菜谱提交')"
              >复制当前菜谱</el-button
            >
            <div v-if="selectedPerson == 0">
              <el-button
                v-if="configValue == 1 && canteenRoles.length > 0"
                style="background-color: #4c6ee2; color: white"
                size="small"
                @click="handleSubmit('提交')"
                >待提交审核</el-button
              >
              <el-button
                v-if="configValue == 2 && canteenRoles.length > 0"
                style="color: white"
                size="small"
                @click="handleSubmit('已提交审核中')"
                type="warning"
                >已提交审核中</el-button
              >
              <el-button
                v-if="adminRoles.length > 0 && configValue == 2"
                style="background-color: #4c6ee2; color: white"
                size="small"
                @click="handleSubmit('待审核')"
                >待审核</el-button
              >
              <el-button
                v-if="configValue == 3 && canteenRoles.length > 0"
                style="background-color: #4c6ee2; color: white"
                size="small"
                @click="handleSubmit('审核通过')"
                >审核结果: 审核通过</el-button
              >
              <el-button
                v-if="configValue == 3 && adminRoles.length > 0"
                style="background-color: #4c6ee2; color: white"
                size="small"
                @click="handleSubmit('已同意')"
              >
                审核结果: 已同意</el-button
              >
              <!-- <el-button v-if="configValue==3" style="color: white;" size="small" @click="handleSubmit" type="primary">审核通过</el-button>  -->
              <el-button
                v-if="configValue == 4 && canteenRoles.length > 0"
                style="color: white"
                size="small"
                type="danger"
                @click="handleSubmit('提交')"
                >审核不通过,请重新提交</el-button
              >
              <el-button
                v-if="configValue == 4 && adminRoles.length > 0"
                style="color: white"
                size="small"
                type="danger"
                @click="handleSubmit('提交')"
                >已拒绝</el-button
              >
            </div>

            <el-button
              type="warning"
              size="small"
              plain
              icon="el-icon-download"
              @click="handleExport(0)"
              >导出</el-button
            >

            <!-- <el-button
              type="warning"
              size="small"
              plain
              icon="el-icon-download"
              @click="handleExport(1)"
              >导出轻食菜谱</el-button
            > -->
            <el-button size="small" @click="resetSearch">重置</el-button>
          </div>
        </div>
        <!-- 加载状态显示 -->
        <!-- <div v-if="loading" class="loading-container">加载中...</div> -->
        <!-- 错误状态显示 -->
        <!-- <div v-else-if="error" class="error-container">{{ error }}</div> -->
      </div>
      <div style="position: relative" v-if="duplicateFoodItems.length > 0">
        <el-collapse accordion>
          <el-collapse-item
            :title="
              '您有' +
              duplicateFoodItems.length +
              '个重复菜品: ' +
              duplicateFoodNames.join('、')
            "
          >
            <div
              v-for="(item, index) in duplicateFoodItems"
              :key="item.foodName"
              style="margin-bottom: 15px"
            >
              <div style="display: flex">
                <h4 style="color: #f56c6c; margin-bottom: 10px">
                  {{ index + 1 }}.{{ item.foodName }} (共出现{{ item.count }}次)
                </h4>
              </div>
              <el-row :gutter="10">
                <el-col
                  :span="6"
                  v-for="(v, index) in item.occurrences"
                  :key="index"
                >
                  <div
                    style="
                      background: #f5f7fa;
                      padding: 8px;
                      border-radius: 4px;
                    "
                  >
                    <div>日期: {{ v.date }}</div>
                    <div>菜品: {{ v.foodName }}</div>
                    <div>餐别: {{ v.mealType }}</div>
                    <div>套餐: {{ v.comboName }}</div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <el-table
        :data="tableData"
        border
        style="width: 100%"
        v-loading="tableLoading"
      >
        <!-- 日期列 -->
        <el-table-column
          prop="date"
          :label="title + '期'"
          width="80"
          align="center"
        ></el-table-column>

        <!-- 早餐列组 -->
        <el-table-column
          label="早餐"
          prop="breakfast"
          align="center"
          v-if="hasBreakfast"
        >
          <el-table-column
            v-for="combo in breakfastCombos"
            :key="'breakfast-' + combo"
            :prop="'breakfast.' + combo"
            :label="combo"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.breakfast[combo]">
                <div @click="deailOnclick(scope.row.breakfast[combo])">{{ scope.row.breakfast[combo].foodName }}</div>
                <div class="price" @click="deailOnclick(scope.row.breakfast[combo])">
                  {{ scope.row.breakfast[combo].price }}元
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 中餐列组 -->
        <el-table-column
          label="中餐"
          prop="lunch"
          align="center"
          v-if="hasLunch"
        >
          <el-table-column
            v-for="combo in lunchCombos"
            :key="'lunch-' + combo"
            :prop="'lunch.' + combo"
            :label="combo"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.lunch[combo]" >
                <div @click="deailOnclick(scope.row.lunch[combo])">{{ scope.row.lunch[combo].foodName }}</div>
                <div class="price" @click="deailOnclick(scope.row.lunch[combo])">{{ scope.row.lunch[combo].price }}元</div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- 晚餐列组 (如果有数据) -->
        <el-table-column
          label="晚餐"
          prop="dinner"
          align="center"
          v-if="hasDinner"
        >
          <el-table-column
            v-for="combo in dinnerCombos"
            :key="'dinner-' + combo"
            :prop="'dinner.' + combo"
            :label="combo"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <div v-if="scope.row.dinner[combo]">
                <div @click="deailOnclick(scope.row.dinner[combo])">{{ scope.row.dinner[combo].foodName }}</div>
                <div class="price" @click="deailOnclick(scope.row.dinner[combo])">{{ scope.row.dinner[combo].price }}元</div>
              </div>
            </template>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>

    <div>
      <combodialogull
    :row="currentRow"
    :visible="dialogVisible"
    @update-success="fetchData"
  />
    </div>
    
  </div>
</template>

<script>
import combodialogull from "./combodialogull.vue"
import {
  getListTableComboResipe,
  getListTableComboRecipeList,
  getListTableComboRecipeHistory,
  getTableComboRecipeType,
  getTableComboEditRecipe,
  foodComboRecipeCopy,
  exportMenu,
  exportQinsMenu,
  ComboParticulars
} from "@/api/combo";
export default {
  name:"cookbookIndex",
  components:{combodialogull},
  data() {
    return {
      currentRow: {},
      dialogVisible:false,
      params: {
        pageNum: 1,
        pageSize: 10,
        beginDate: "",
        endDate: "",
      },
      total: 0,
      seletedTime: "", //默认当前时间
      // 上拉加载更多相关数据
      pageNum: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      loadingMore: false, // 加载更多状态
      hasMoreData: true, // 是否还有更多数据
      tableLoading: true, //是否加载中
      searchForm: {
        ingredientsCode: "",
        ingredientsName: "",
        supplierName: "",
        price: "",
        applyDate: [],
        createDate: [],
      },
      // 审核状态
      configValue: 1, //1：待提交审核\n2：已提交，待审核\n3：审核通过\n4：审核不通过
      title: 0,
      // 左侧tabs数据
      tabsList: [],
      // 表格的原始数据
      originalData: {},
      // 转换后的数据
      transformedData: [],
      // 加载状态
      loading: false,
      // 错误信息
      error: "",
      // 日期范围
      dateRange: [],
      // 选中的标签页
      activeTab: "unreleased",
      // 左侧tab默认显示
      selectedPerson: 0,
      adminRoles: [], //超级管理员  和后勤管理员
      canteenRoles: [], //食堂管理员

      tableData: [], // 格式化后的表格数据
      breakfastCombos: [], // 早餐套餐列表
      lunchCombos: [], // 中餐套餐列表
      dinnerCombos: [], // 晚餐套餐列表
      hasBreakfast: false, // 是否有早餐数据
      hasLunch: false, // 是否有中餐数据
      hasDinner: false, // 是否有晚餐数据
      duplicateFoodItems: [], // 存储重复的菜品
      duplicateFoodNames: [], // 存储重复菜品的名称数组
    };
  },
  mounted() {
    this.adminRoles = this.$store.state.user.roles.filter(
      (el) => el == "admin" || el == "rear_admin"
    );
    this.canteenRoles = this.$store.state.user.roles.filter(
      (el) => el == "canteen_admin"
    );

    console.log("获取角色", this.adminRoles, this.canteenRoles);
    // 右侧表格
    this.fetchMenuData();
    // 左侧tab
    this.getTableComboRecipeList();
    // 查询审核状态
    this.getListTableComboRecipeType();
  },
  methods: {
    async deailOnclick(val) {
      if (this.selectedPerson != 0) {
        return false
      }

      console.log(val)
      const res = await ComboParticulars(val.comboId);
      if (res.code == 200) {
        this.currentRow = res.data;
        this.dialogVisible = true
      }
      // this.$router.push("/combo?comboCode=" + val.comboCode)
      console.log(val, this.selectedPerson)
      
    },
    fetchData() {
      this.dialogVisible = false;
    },
    // 转换数据为表格所需格式
    transformData() {
      // 重置状态
      this.breakfastCombos = [];
      this.lunchCombos = [];
      this.dinnerCombos = [];
      this.hasBreakfast = false;
      this.hasLunch = false;
      this.hasDinner = false;
      this.tableData = [];
      this.duplicateFoodItems = []; // 重置重复菜品数组

      if (!this.originalData || Object.keys(this.originalData).length === 0) {
        return;
      }

      // 创建一个Map来存储每个菜品出现的所有位置信息
      const foodOccurrencesMap = new Map();
      // 创建一个Map来存储每个菜品的基本信息
      const foodInfoMap = new Map();

      // 1. 收集所有套餐名称和统计菜品出现位置
      const allBreakfastCombos = new Set();
      const allLunchCombos = new Set();
      const allDinnerCombos = new Set();

      // 定义需要过滤的套餐类型
      const targetCombos = ["A", "B", "C", "D"];

      // 遍历所有日期
      Object.keys(this.originalData).forEach((date) => {
        const dayData = this.originalData[date];

        // 处理早餐
        if (dayData["早餐meals"] && dayData["早餐meals"].length > 0) {
          this.hasBreakfast = true;
          dayData["早餐meals"].forEach((combo) => {
            allBreakfastCombos.add(combo.comboName);

            // 记录菜品出现位置 - 只处理A/B/C/D套餐
            if (
              combo.listItem &&
              combo.listItem.length > 0 &&
              targetCombos.includes(combo.comboName)
            ) {
              combo.listItem.forEach((item) => {
                if (item.foodDish && item.foodDish.foodName) {
                  const foodName = item.foodDish.foodName;
                  // 存储菜品基本信息
                  if (!foodInfoMap.has(foodName)) {
                    foodInfoMap.set(foodName, item.foodDish);
                  }
                  // 记录出现位置
                  if (!foodOccurrencesMap.has(foodName)) {
                    foodOccurrencesMap.set(foodName, []);
                  }
                  foodOccurrencesMap.get(foodName).push({
                    date: date,
                    mealType: "早餐",
                    comboName: combo.comboName,
                    comboCode: combo.comboCode,
                    comboId:combo.comboId,
                    foodName: foodName, // 将菜品名称追加到occurrences字段中
                  });
                }
              });
            }
          });
        }

        // 处理中餐
        if (dayData["中餐meals"] && dayData["中餐meals"].length > 0) {
          this.hasLunch = true;
          dayData["中餐meals"].forEach((combo) => {
            allLunchCombos.add(combo.comboName);

            // 记录菜品出现位置 - 只处理A/B/C/D套餐
            if (
              combo.listItem &&
              combo.listItem.length > 0 &&
              targetCombos.includes(combo.comboName)
            ) {
              combo.listItem.forEach((item) => {
                if (item.foodDish && item.foodDish.foodName) {
                  const foodName = item.foodDish.foodName;
                  // 存储菜品基本信息
                  if (!foodInfoMap.has(foodName)) {
                    foodInfoMap.set(foodName, item.foodDish);
                  }
                  // 记录出现位置
                  if (!foodOccurrencesMap.has(foodName)) {
                    foodOccurrencesMap.set(foodName, []);
                  }
                  foodOccurrencesMap.get(foodName).push({
                    date: date,
                    mealType: "中餐",
                    comboCode: combo.comboCode,
                     comboId:combo.comboId,
                    comboName: combo.comboName,
                    foodName: foodName, // 将菜品名称追加到occurrences字段中
                  });
                }
              });
            }
          });
        }

        // 处理晚餐
        if (dayData["晚餐meals"] && dayData["晚餐meals"].length > 0) {
          this.hasDinner = true;
          dayData["晚餐meals"].forEach((combo) => {
            allDinnerCombos.add(combo.comboName);

            // 记录菜品出现位置 - 只处理A/B/C/D套餐
            if (
              combo.listItem &&
              combo.listItem.length > 0 &&
              targetCombos.includes(combo.comboName)
            ) {
              combo.listItem.forEach((item) => {
                if (item.foodDish && item.foodDish.foodName) {
                  const foodName = item.foodDish.foodName;
                  // 存储菜品基本信息
                  if (!foodInfoMap.has(foodName)) {
                    foodInfoMap.set(foodName, item.foodDish);
                  }
                  // 记录出现位置
                  if (!foodOccurrencesMap.has(foodName)) {
                    foodOccurrencesMap.set(foodName, []);
                  }
                  foodOccurrencesMap.get(foodName).push({
                    date: date,
                    mealType: "晚餐",
                    comboCode: combo.comboCode,
                     comboId:combo.comboId,
                    comboName: combo.comboName,
                    foodName: foodName, // 将菜品名称追加到occurrences字段中
                  });
                }
              });
            }
          });
        }
      });

      // 筛选出重复的菜品（出现次数大于1）并添加完整上下文信息
      this.duplicateFoodItems = Array.from(foodOccurrencesMap.entries())
        .filter(([foodName, occurrences]) => occurrences.length > 1)
        .map(([foodName, occurrences]) => ({
          foodName: foodName,
          count: occurrences.length,
          occurrences: occurrences,
        }));

      // 提取重复菜品名称数组用于显示
      this.duplicateFoodNames = this.duplicateFoodItems.map(
        (item) => item.foodName
      );

      // 转换为数组并排序
      this.breakfastCombos = Array.from(allBreakfastCombos).sort();
      this.lunchCombos = Array.from(allLunchCombos).sort();
      this.dinnerCombos = Array.from(allDinnerCombos).sort();

      // 2. 格式化表格数据
      Object.keys(this.originalData).forEach((date) => {
        const dayData = this.originalData[date];
        const rowData = {
          date: date,
          breakfast: {},
          lunch: {},
          dinner: {},
        };

        // 初始化所有套餐为null
        this.breakfastCombos.forEach((combo) => {
          rowData.breakfast[combo] = null;
        });
        this.lunchCombos.forEach((combo) => {
          rowData.lunch[combo] = null;
        });
        this.dinnerCombos.forEach((combo) => {
          rowData.dinner[combo] = null;
        });

        // 填充早餐数据
        if (dayData["早餐meals"] && dayData["早餐meals"].length > 0) {
          dayData["早餐meals"].forEach((combo) => {
            if (combo.listItem && combo.listItem.length > 0) {
              // 循环拼接所有foodName
              const foodNames = combo.listItem
                .map((item) =>
                  item.foodDish
                    ? `${item.foodDish.foodName}${
                        item.foodDish.huisType == 1 ? "🐷" : ""
                      }${
                        item.foodDish.peType == 1
                          ? "🌶"
                          : item.foodDish.peType == 2
                          ? "🌶🌶"
                          : item.foodDish.peType == 3
                          ? "🌶🌶🌶"
                          : ""
                      }`
                    : ""
                )
                .join("\n");
              rowData.breakfast[combo.comboName] = {
                foodName: foodNames,
                price: combo.price || 0,
                comboCode: combo.comboCode,
                                 comboId:combo.comboId,

              };
            }
          });
        }

        // 填充中餐数据
        if (dayData["中餐meals"] && dayData["中餐meals"].length > 0) {
          dayData["中餐meals"].forEach((combo) => {
            if (combo.listItem && combo.listItem.length > 0) {
              const foodNames = combo.listItem
                .map((item) =>
                  item.foodDish
                    ? `${item.foodDish.foodName}${
                        item.foodDish.huisType == 1 ? "🐷" : ""
                      }${
                        item.foodDish.peType == 1
                          ? "🌶"
                          : item.foodDish.peType == 2
                          ? "🌶🌶"
                          : item.foodDish.peType == 3
                          ? "🌶🌶🌶"
                          : ""
                      }`
                    : ""
                )
                .join("\n");
              rowData.lunch[combo.comboName] = {
                foodName: foodNames,
                price: combo.price || 0,
                comboCode: combo.comboCode,
                 comboId:combo.comboId
              };
            }
          });
        }

        // 填充晚餐数据
        if (dayData["晚餐meals"] && dayData["晚餐meals"].length > 0) {
          dayData["晚餐meals"].forEach((combo) => {
            if (combo.listItem && combo.listItem.length > 0) {
              // const foodItem = combo.listItem[0];
              const foodNames = combo.listItem
                .map((item) =>
                  item.foodDish
                    ? `${item.foodDish.foodName}${
                        item.foodDish.huisType == 1 ? "🐷" : ""
                      }${
                        item.foodDish.peType == 1
                          ? "🌶"
                          : item.foodDish.peType == 2
                          ? "🌶🌶"
                          : item.foodDish.peType == 3
                          ? "🌶🌶🌶"
                          : ""
                      }`
                    : ""
                )
                .join("\n");
              rowData.dinner[combo.comboName] = {
                foodName: foodNames,
                price: combo.price || 0,
                comboCode: combo.comboCode,
                                 comboId:combo.comboId

              };
            }
          });
        }

        this.tableData.push(rowData);
      });
    },
    // 重置
    resetSearch() {
      this.selectedPerson = 0; //左侧tab恢复默认
      this.params.pageNum = 1;
      this.params.pageSize = 10;
      this.params.beginDate = "";
      this.params.endDate = "";
      this.fetchMenuData();
      this.getTableComboRecipeList();
    },
    handleScroll() {
       if (this.tabsList.length >= this.total) {
         return false;
     }
      const scrollElement = this.$refs.scrollableArea;
      const scrollTop = scrollElement.scrollTop;
      const scrollHeight = scrollElement.scrollHeight;
      const clientHeight = scrollElement.clientHeight;

      // 当滚动到距离底部20px时触发加载更多
      if (
        scrollTop + clientHeight >= scrollHeight - 20 &&
        !this.loadingMore &&
        this.hasMoreData
      ) {
        console.log("触底加载更多", this.loadingMore, this.pageNum);
        this.loadingMore = true;
        this.pageNum++;
        this.params.pageNum = this.pageNum;
        this.getTableComboRecipeList();
      }
    },
    // 查询审核状态
    async getListTableComboRecipeType() {
      const response = await getTableComboRecipeType();
      this.configValue = response.data.configValue;
      console.log("查询审核状态this.configValue", this.configValue);
    },
    // 获取左侧tab数据
    async getTableComboRecipeList() {
      if (this.pageNum != 1) {
         if (this.tabsList.length >= this.total) {
         return false;
     }
      }
        
      // 防止重复加载
      // if (this.loadingMore || !this.hasMoreData) return;
      try {
        const response = await getListTableComboRecipeList(this.params);
        // 首次加载数据
        if (this.pageNum === 1) {
          this.tabsList = response.data.list || [];
          this.total = response.data.total || 0;

          // 检查是否还有更多数据
          if (this.tabsList.length >= this.total) {
            this.hasMoreData = false;
          }
        }  else {// 加载更多数据
          const newData = response.data.list || [];
          this.tabsList.push(...newData);

          // 更新加载状态
          this.loadingMore = false;

          // 检查是否还有更多数据
          if (this.tabsList.length >= this.total) {
            this.hasMoreData = false;
          }

          return; // 加载更多时不需要执行下面的代码
        }

         // 设置选中的时间段
         if (this.tabsList.length > 0) {
          this.seletedTime = 
            this.tabsList[0].history_begin_date +
            "至" +
            this.tabsList[0].history_end_date;
        }
        
        // 首次渲染表格标题
        if (this.tabsList.length > 0) {
          this.title = this.tabsList[0].history_version;
        }
        
        console.log("获取左侧tab数据", this.title, this.tabsList);
        

        // this.tabsList =response.data.list
        // 首次渲染表格标题
        // this.title = this.tabsList[0].history_version;
        // console.log("获取左侧tab数据", this.title);
      } catch (err) {
        console.error("API请求错误:", err);
        this.loadingMore = false; // 出错时重置加载状态
      } finally {
        this.loading = false;
      }
    },

    // 模拟获取数据
    async fetchMenuData() {
      this.tableLoading = true;
      this.error = "";

      try {
        const response = await getListTableComboResipe();
        this.originalData = response.data;
        // 转换数据为表格格式
        this.transformData();
      } catch (err) {
        // this.error = `获取菜单数据失败：${err.message || "未知错误"}`;
        console.error("API请求错误:", err);
      } finally {
        this.tableLoading = false;
      }
    },
    // 获取左侧tab从第二个数据开始的历史表格数据
    async fetchMenuDataHistory() {
      this.tableLoading = true;
      this.error = "";

      try {
        const params = {
          beginDate: this.params.beginDate,
          endDate: this.params.endDate,
          historyVersion: this.params.historyVersion,
        };
        const response = await getListTableComboRecipeHistory(params);
        this.originalData = response.data;
        console.log("打印从第二个开始的右侧表格数据", response);
        // 转换数据为表格格式
        this.transformData();
      } catch (err) {
        // this.error = `获取菜单数据失败：${err.message || "未知错误"}`;
        console.error("API请求错误:", err);
      } finally {
        this.tableLoading = false;
      }
    },
    // 日期范围变化处理
    onDateChange(range) {
      if (range) {
        console.log("日期范围已更改为:", range);
        this.params.beginDate = range[0];
        this.params.endDate = range[1];
        this.getTableComboRecipeList();
        // 实际项目中可以根据日期范围重新获取数据
        // this.fetchMenuDataByDateRange(range);
      }
    },
    // 左侧tab切换
    selectPerson(type) {
      console.log(
        "切换了",
        this.selectedPerson,
        this.tabsList[type],
        this.params
      );
      // 初始化顶部重复菜品数据
      this.duplicateFoodItems = [];

      this.selectedPerson = type;
      this.title = this.tabsList[type].history_version;
      this.params.beginDate = this.tabsList[type].history_begin_date;
      this.params.endDate = this.tabsList[type].history_end_date;
      this.params.historyVersion = this.tabsList[type].history_version;
      this.seletedTime =
        this.tabsList[type].history_begin_date +
        "至" +
        this.tabsList[type].history_end_date;

      if (this.selectedPerson == 0) {
        this.fetchMenuData();
        // 查询审核状态
        this.getListTableComboRecipeType();
        return;
      }
      this.originalData = [];
      // 获取右侧表格数据
      this.fetchMenuDataHistory();
    },
    async requestConfirm(type) {
      const result = await getTableComboEditRecipe({ configValue: type });
      if (result.code == 200) {
        // 审核通过
        this.$message({
          type: type == 3 ? "success" : "error",
          message: type == 3 ? "已同意" : type == 4 ? "已拒绝" : "已取消",
        });
      }
      // 查询审核状态
      this.getListTableComboRecipeType();
    },
    // 添加提交按钮处理方法
    handleSubmit(type) {
      if (type === "已提交待审核")
        return this.$message({ type: "warning", message: "请等待审核" });
      if (type === "已提交待审核")
        return this.$message({ type: "warning", message: "请等待审核" });
      if (type === "提交") {
        if (
          this.adminRoles.length > 0 &&
          (this.configValue == 4 || this.configValue == 3)
        )
          return;
        this.$confirm("确定要提交当前菜谱数据吗？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const result = await getTableComboEditRecipe({ configValue: 2 });
            if (result.code == 200) {
              // 查询审核状态
              this.getListTableComboRecipeType();
              console.log("提交菜谱数据", result);
              this.$message({ type: "success", message: "提交成功" });
            } else {
              this.$message({ type: "error", message: result.msg });
            }
          })
          .catch(() => {
            this.$message({ type: "info", message: "已取消提交" });
          });
      }
      if (type === "待审核") {
        this.$confirm("是否审核通过?", "确认信息", {
          distinguishCancelAndClose: true,
          confirmButtonText: "通过",
          cancelButtonText: "不通过",
        })
          .then(() => {
            console.log("已同意");
            this.requestConfirm(3);
          })
          .catch((action) => {
            if (action === "cancel") {
              console.log("已拒绝", action);
              // 点击了取消按钮，也就是现在的不通过
              this.requestConfirm(4);
            }
            console.log("已拒绝", action);
          });
      }
      if (type === "菜谱提交") {
        console.log("走到这里", type);
        this.$confirm("是否提交当前菜谱?", "确认信息", {
          distinguishCancelAndClose: true,
          confirmButtonText: "提交",
          cancelButtonText: "取消",
        })
          .then(() => {
            this.submitConfirm();
          })
          .catch((action) => {});
      }
    },
    async submitConfirm() {
      const loading = this.$loading({
        lock: true,
        text: "提交中,请稍后",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      const data = this.tabsList[this.selectedPerson];
      const T = {
        historyBeginDate: data.history_begin_date,
        historyEndDate: data.history_end_date,
        historyVersion: data.history_version,
      }
      const result = await foodComboRecipeCopy(T);
      if (result.code == 200) {
        setTimeout(() => {
          loading.close();
        }, 500);
        this.$message({ type: "success", message: "提交成功" });
      }
    },

    // 添加导出按钮处理方法
    async handleExport(val) {
         const data = {
        historyBeginDate: this.tabsList[this.selectedPerson].history_begin_date,
        historyEndDate: this.tabsList[this.selectedPerson].history_end_date,
        menuType: this.selectedPerson == 0 ? 0 : 1,
        historyVersion: this.tabsList[this.selectedPerson].history_version,
      };
      // if (val == 1) {
      //   const res = await exportQinsMenu(data)
      //   return false
      // }

      console.log("导出菜谱数据", this.selectedPerson, this.tabsList, {
        historyBeginDate: this.tabsList[this.selectedPerson].history_begin_date,
        historyEndDate: this.tabsList[this.selectedPerson].history_end_date,
        menuType: 0,
        historyVersion: this.tabsList[this.selectedPerson].history_version,
      });
     
      this.tableDownload(
        val == 1 ? '/food/combo/export/light/menu' : "food/combo/export/menu",
        data,
        `菜谱导出${data.historyBeginDate + "-" + data.historyEndDate}.${ val == 1 ? "docx" : "xlsx"}`
      ).then((result) => {
        console.log("是否导出成功", result);
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-collapse {
  position: absolute;
  z-index: 9;
  top: -30px;
  width: 100%;
  border-bottom: none;
  .el-collapse-item {
    .el-collapse-item__header {
      height: 30px;
      line-height: 30px;
      color: #1989fa !important;
    }
  }
}
.price {
  font-size: 12px;
  margin-top: 4px;
  font-weight: bold;
}

.el-table .cell {
  white-space: normal;
  word-break: break-all;
}
::v-deep.el-icon-check:before {
  margin-left: 5px !important;
  margin-top: 5px !important;
}
/* 整体容器布局 */
.menu-container {
  display: flex;
  gap: 20px;
  padding: 20px;
  height: 100%;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 左侧面板样式 */
.left-panel {
  width: 300px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}
/* 滚动区域样式 */
.scrollable-area {
  // flex: 1;
  overflow-y: auto;
  // margin-top: 10px;
  height: calc(100vh - 32px);
  /* 设置自定义滚动条 */
  &::-webkit-scrollbar {
    width: 6px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 3px;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
  }
}

/* 标题和按钮容器布局 */
.title-actions-container {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  width: 100%;
}

/* 左侧占位元素 */
.title-wrapper {
  flex: 1;
}

/* 表格标题样式 */
.table-title {
  text-align: center;
  color: #333;
  font-size: 24px;
  font-weight: bold;
  margin: 0;
  white-space: nowrap;
}

/* 右侧按钮容器 */
.actions-wrapper {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

/* 按钮样式覆盖 */
::v-deep .actions-wrapper .el-button {
  min-width: 80px;
}

.panel-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 20px;
  color: #333;
}

.date-picker {
  margin-bottom: 20px;
}

.tabs {
  margin-bottom: 20px;
}

.person-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding-bottom: 10px;
}
/* 加载更多样式 */
.loading-more {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 15px;
  color: #666;
  font-size: 14px;
}

.loading-more .el-icon-loading {
  margin-right: 8px;
}

/* 没有更多数据样式 */
.no-more-data {
  text-align: center;
  padding: 15px;
  color: #999;
  font-size: 14px;
}

.person-card {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  &:hover {
    border-color: #1989fa;
    box-shadow: 0 2px 8px rgba(25, 137, 250, 0.1);
  }
  &.total {
    border: 2px solid #ff6b6b;
    background-color: #fff5f5;
  }
  /* 选中样式 - 修改为蓝色外边框、蓝色背景和右下角对勾 */
  &.selected {
    border: 2px solid #1989fa;
    background-color: #e6f4ff;
    box-shadow: 0 0 0 2px rgba(25, 137, 250, 0.1);
  }
}
// * 对勾图标样式 */
.check-icon {
  position: absolute;
  bottom: 0;
  right: 0;
  background-color: #1989fa;
  color: white;
  width: 24px;
  height: 19px;
  border-top-left-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.person-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.person-header .el-avatar {
  margin-right: 10px;
}

.person-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  flex: 1;
}

.total-amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff6b6b;
}

.person-details {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.detail-item span:first-child {
  color: #666;
}

.detail-item span:last-child {
  color: #333;
  font-weight: 500;
}

.released-amount {
  color: #1989fa;
}

/* 右侧面板样式 */
.right-panel {
  flex: 1;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

/* 原有表格样式 */
::v-deep .el-table .cell {
  white-space: pre-line;
}

.cell-wrap .cell {
  white-space: pre-line; /* 识别 \n 并换行 */
}

.menu-table-container {
  padding: 0;
  font-family: "Arial", sans-serif;
}

.table-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 24px;
  font-weight: bold;
}

.el-table {
  margin-bottom: 20px;
}

.el-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

.el-table td {
  vertical-align: middle;
}

.table-footer {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  border-top: 1px solid #eee;
  padding-top: 15px;
  margin-top: 10px;
}

/* 加载和错误状态样式 */
.loading-container,
.error-container {
  text-align: center;
  padding: 40px 0;
  color: #666;
}

.error-container {
  color: #f56c6c;
}
</style>
